package com.sx.pipeline.ui.chat.contact

import android.os.Bundle
import android.view.View
import com.alibaba.android.arouter.launcher.ARouter
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.adapter.SortContactAdapter
import com.sx.pipeline.app.base.CYDataBindingBaseFragment
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.app.model.CYBaseViewModel
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.SideBar
import com.sx.pipeline.databinding.FragContactBinding
import com.sx.pipeline.repos.http.res.ContactUserVo
import com.sx.pipeline.ui.chat.ChatVM
import java.util.*


/**
 * @Author: YY
 * @Date: 2022/4/7
 * @Description: 联系人列表
 */
class ContactFragment :
    CYDataBindingBaseFragment<FragContactBinding, ChatVM>(R.layout.frag_contact),
    View.OnClickListener {
    var list: MutableList<ContactUserVo> = ArrayList()

    companion object {
        fun newInstance(position: Int) =
            ContactFragment().apply {
                arguments = Bundle().apply {
                    putInt(IntentKey.ID, position)
                }
            }
    }


    private fun initRv(contactData: List<ContactUserVo>) {
        list = ArrayList()
        for (i in contactData.indices) {
            list.add(
                ContactUserVo(
                    contactData[i].userUnitId,
                    contactData[i].userName,
                    contactData[i].avatar
                )
            )
        }
        list.sort() // 对list进行排序，需要让User实现Comparable接口重写compareTo方法
        val adapter = SortContactAdapter(context, list)
        mBinding.listView.adapter = adapter
    }

    override fun initData() {
        mBinding.setVariable(BR.onClick, this)
        mViewModel.getRongContact("")
    }

    override fun initViewObservable() {
        super.initViewObservable()
        observe(mViewModel.contactListEvent) {
            it?.let { it1 -> initRv(it1) }
        }
    }

    override fun initListener() {
        super.initListener()
        mBinding.sideBar.setOnStrSelectCallBack(object : SideBar.ISideBarSelectCallBack {
            override fun onSelectStr(index: Int, selectStr: String) {
                for (i in list.indices) {
                    if (selectStr.equals(list.get(i).getFirstLetter(), ignoreCase = true)) {
                        mBinding.listView.setSelection(i) // 选择到首字母出现的位置
                        return
                    }
                }
            }
        })
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            //组织架构
            R.id.tv_organize-> ARouter.getInstance().build(RoutePath.Chat.CHAT_ORGANIZE).navigation()
            R.id.tv_group -> ARouter.getInstance().build(RoutePath.Chat.CHAT_GROUP).navigation()
        }
    }


}